package com.wchat.server.handler;

import cn.hutool.core.util.ObjectUtil;
import com.wchat.bean.model.MsgPayload;
import com.wchat.bean.model.Session;
import com.wchat.server.ClientManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author : willian fu
 * @date : 2020/5/30
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class MessageHandler extends SimpleChannelInboundHandler<MsgPayload> {

    @Autowired
    private PackageHandler packageHandler;

    @Autowired
    private ClientManager clientManager;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MsgPayload msgPayload) throws Exception {
        packageHandler.handler(clientManager.getSession(ctx.channel()), msgPayload);
    }

    /**
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Session session = clientManager.getSession(ctx.channel());
        log.error("客户端[{}]通信出现异常:{}", session.getUserId(), cause.getMessage());
    }

    /**
     * Do nothing by default, sub-classes may override this method.
     *
     * @param ctx
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        clientManager.offline(ctx.channel());
        super.handlerRemoved(ctx);
    }
}
